/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.pay.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.bean.FinancialProjectBean;
import com.yunhoo.base.db.dao.DepartmentDao;
import com.yunhoo.base.db.dao.FinancialProjectDao;
import com.yunhoo.base.db.impl.PersonImpl;
import com.yunhoo.base.model.AbroadGroupCurrency;
import com.yunhoo.base.model.AbroadGroupGroup;
import com.yunhoo.base.model.ClassCode;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.PayStyle;
import com.yunhoo.base.model.Person;
import com.yunhoo.pay.db.impl.AbroadGroupCheckImpl;
import com.yunhoo.pay.db.impl.AbroadGroupImpl;
import com.yunhoo.pay.db.impl.VoucherPubImpl;
import com.yunhoo.pay.model.AbroadGroupBackorCollar;
import com.yunhoo.pay.model.AbroadGroupCost;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.model.VouCheckInfo;
import com.yunhoo.pay.util.BillOrder;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.Disabled;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.pay.util.ToolsMethed;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.event.TreeSelectionChangeEvent;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "abroadGroupCheckBean")
@SessionScoped
public class AbroadGroupCheckBean {

    private Expense abroad = null;                         //主表 
    private AbroadGroupCost cost = null;                   //费用明细表
    private AbroadGroupCurrency currency = null;           //币种表
    private AbroadGroupGroup group = null;                 //出国团组表
    private AbroadGroupBackorCollar back = null;           //退领表
    private List<AbroadGroupCost> costLi = null;           //费用明细表list
    private DataModel costModel = null;
    private DataModel backModel = null;
    private DataModel abroadModel = null;
    private List<AbroadGroupBackorCollar> backLi = null;    //退领表list
    private List<AbroadGroupGroup> groupLi = null;
    private List<AbroadGroupCurrency> currencyLi = null;
    private List<Expense> abroadList = null;
    private boolean showAble = true;
    private boolean addOrUpdate = false;
    private boolean deleteable = false;
    private boolean saveOrNot = false;
    private boolean updateOrNot = false;
    private boolean submitOrNot = false;
    private boolean printAble = false;
    private Disabled dis = new Disabled();
    private QueryVouchers qta = new QueryVouchers();
    private int index;
    private int costLiSize;
    private LinkedList<Expense> linkedli = new LinkedList<Expense>();
    private ClassCode classcode = new ClassCode();
    private List<ClassCode> classlist = new ArrayList();
    private List<SelectItem> selectItemList;
    private List<SelectItem> payStyleList;
    private String payWay;
    private String payWayType;
    private Double backTotal = 0d;
    private DataModel abroadCheckViewModel = new ListDataModel();
    private static DaoManager daom;
    private static DepartmentDao dao;
    private static FinancialProjectDao finProjdao;
    private DataModel<FinancialProject> finProjModel = null;
    private String status = "";

    public AbroadGroupCheckBean() {
        daom = DaoConfig.getDaoManager();
        dao = (DepartmentDao) daom.getDao(DepartmentDao.class);
        finProjdao = (FinancialProjectDao) daom.getDao(FinancialProjectDao.class);
        initProperty();
        initFunction();
        initStatus();
        //queryAbroadList();
        initPayStyleList();
        initFinProjList();
        initDate();
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -10);
        Date begin = calendar.getTime();
        Date end = new Date();
        qta.setNumDateStart(begin);
        qta.setNumDateEnd(end);
    }

    private void initStatus() {
        saveOrNot = true;
        addOrUpdate = true;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = true;
        printAble = true;
    }

    private void initFinProjList() {
        if (finProjModel == null) {
            finProjModel = new ListDataModel<FinancialProject>();
        }
        try {
            List<FinancialProject> finli = finProjdao.queryAll(new FinancialProject(true));
            finProjModel.setWrappedData(finli);
        } catch (SQLException ex) {
            Logger.getLogger(FinancialProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //属性初始化
    private void initProperty() {
        abroadModel = new ListDataModel();
        abroad = new Expense();
        cost = new AbroadGroupCost();
        currency = new AbroadGroupCurrency();
        group = new AbroadGroupGroup();
        back = new AbroadGroupBackorCollar();
        classcode = new ClassCode();
        abroad.setAuditor(curPerName().trim());
        selectItemList = new ArrayList();
        classlist = IbatisTemplate.queryForList("classCode.queryClassCodeAll", classcode);
        for (ClassCode c : classlist) {
            selectItemList.add(new SelectItem(c.getCode(), c.getName()));
        }
    }

    //方法初始化
    private void initFunction() {
        groupLi = AbroadGroupImpl.getAbroadGroupGroup();
        currencyLi = AbroadGroupImpl.getAbroadGroupCurrency();
        costLi = new ArrayList();
        backLi = new ArrayList();
        costModel = new ListDataModel();
        backModel = new ListDataModel();
    }

    //支付方式选择列表 
    public final void initPayStyleList() {
        List<PayStyle> Styleli = AbroadGroupImpl.getPaystyleli();
        payStyleList = new ArrayList();
        for (PayStyle d : Styleli) {
            payStyleList.add(new SelectItem(d.getCode(), d.getName()));
        }
    }

    public void payWayChange(ValueChangeEvent event) {
        String code = (String) event.getNewValue();
        List<PayStyle> li = AbroadGroupImpl.getPaystyleli();
        if (!Null.check(li) && !Null.check(code)) {
            for (PayStyle l : li) {
                if (code.trim().equals(l.getCode().trim())) {
                    abroad.setPayStyle(l);
                    payWayType = l.getType().trim();
                    //System.out.println("payWayType : " + payWayType);
                }
            }
        }
    }

    public void changeCashPaid() {
        if (!Null.check(abroad.getPayStyle().getType())) {
            if (abroad.getPayStyle().getType().equals("0")) {
                abroad.setCashPaid("1");
            } else {
                abroad.setCashPaid("0");
            }
        }
    }

    public void getFirst() {
        if (linkedli.size() == 0) {
            if (abroadList.isEmpty()) {
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(abroadList);
                this.setAbroad(linkedli.getFirst());

                builds();

                dis.setFirst(true);
                dis.setPreviouse(true);
                dis.setNext(false);
                dis.setLast(false);
            }
            if (abroad.getNumberStatus().trim().equals("0")) {
                submitOrNot = true;
            } else {
                submitOrNot = false;
            }
            deleteable = false;
            updateOrNot = false;
        } else {
            this.setAbroad(linkedli.getFirst());

            builds();

            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        index = 0;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void getLast() {
        if (linkedli.size() == 0) {
            if (abroadList.isEmpty()) {
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(abroadList);
                this.setAbroad(linkedli.getLast());

                builds();

                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(false);
                dis.setFirst(false);
            }
            if (abroad.getNumberStatus().trim().equals("0")) {
                submitOrNot = true;
            } else {
                submitOrNot = false;
            }
            deleteable = false;
            updateOrNot = false;
        } else {
            this.setAbroad(linkedli.getLast());

            builds();

            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        index = linkedli.size() - 1;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void next() {
        if (index < linkedli.size() - 1) {
            index++;
            this.setAbroad(linkedli.get(index));

            builds();

            dis.setFirst(false);
            dis.setPreviouse(false);
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了");
            dis.setLast(true);
            dis.setNext(true);
            dis.setFirst(false);
            dis.setPreviouse(false);
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void previouse() {
        if (index > 0) {
            index -= 1;
            this.setAbroad(linkedli.get(index));

            builds();

            dis.setNext(false);
            dis.setLast(false);
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了");
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void cancel() {
        qta = new QueryVouchers();
        status = "";
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        abroadList = AbroadGroupCheckImpl.getAbroadPayList(map);
        abroadModel.setWrappedData(abroadList);
    }
    //选择预算项目

    public void selectProjForQuery() {
        FinancialProject fProj = finProjModel.getRowData();
        qta.getProject().setFinCode(fProj.getFinCode());
        qta.getProject().setFinName(fProj.getFinName());
    }
    //选择部门

    public void selecteDeptForQuery(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        qta.getDept().setCode(dp.getCode());
        qta.getDept().setName(dp.getName());
    }
    //动态查询

    public void queryAbroadList() {
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("number", qta.getNumber().trim());
        map.put("affair", qta.getAffair().trim());
        map.put("projcode", Null.convert(qta.getProject().getFinCode()).trim());
        map.put("deptname", Null.convert(qta.getDept().getName()).trim());
        map.put("cpsn_name", Null.convert(qta.getUser().getCpsn_number()).trim());
        map.put("budgetSource", qta.getBudgetSource().trim());
        map.put("costcode", Null.convert(qta.getCostitem().getCode()).trim());
        map.put("paycode", qta.getPaycode().trim());
        map.put("costClass", qta.getCostClass().trim());
        map.put("costType", qta.getCostTypes().getCode().trim());
        map.put("payStyle", qta.getPayStyle().trim());
        map.put("ticketcode", qta.getTicketcode().trim());
        map.put("numDateStart", qta.getNumDateStart());
        map.put("numDateEnd", qta.getNumDateEnd());
        map.put("auditDateStart", qta.getAuditDateStart());
        map.put("auditDateEnd", qta.getAuditDateEnd());
        map.put("payDateStart", qta.getPayDateStart());
        map.put("payDateEnd", qta.getPayDateEnd());
        map.put("totalStart", qta.getTotalStart());
        map.put("totalEnd", qta.getTotalEnd());
        map.put("checkaccountStart", qta.getCheckaccountStart());
        map.put("checkaccountEnd", qta.getCheckaccountEnd());
        map.put("payaccountStart", qta.getPayaccountStart());
        map.put("payaccountEnd", qta.getPayaccountEnd());
        map.put("sql", Null.convert(status).trim());
        abroadList = AbroadGroupCheckImpl.getAbroadPayList(map);
        abroadModel.setWrappedData(abroadList);
    }

    //选择具体审核条目 并跳转 检查
    public void showAbroadDetail() {
        abroad = (Expense) abroadModel.getRowData();
        index = abroadModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(abroadList);
        showAble = false;
        abroad.setAuditDate(new Date());
        abroad.setPerson(abroad.getUser().getCpsn_name());

        builds();


        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            //System.out.println("submitOrNot=" + submitOrNot);
        }
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        NavigationTool.getSelectedUrl("/page/pay/check/operation/abroadGroupCheck.xhtml");
    }

    //选择具体审核条目 并跳转 支付
    public void showAbroadDetailforPay() {
        abroad = (Expense) abroadModel.getRowData();
        index = abroadModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(abroadList);
        showAble = false;
        abroad.setPayer(curPerName().trim());
        abroad.setPayDate(new Date());
        abroad.setPayaccount(abroad.getCheckaccount());
        abroad.setPerson(abroad.getUser().getCpsn_name());
        abroad.setReceive(abroad.getFeePer().getCpsn_name());
        payWay = abroad.getPayStyle().getCode();

        Map map = new HashMap();
        map.put("number", abroad.getNumber());
        map.put("voutype", "6");
        map.put("orgCode", curOrgCode().trim());
        costLi = AbroadGroupCheckImpl.getAbroadCostLi(map);
        for (int i = 0; i < costLi.size(); i++) {
            costLi.get(i).setLineId(i + 1);
        }
        costModel.setWrappedData(costLi);
        backTotal = 0d;
        backLi = AbroadGroupCheckImpl.getAbroadBackLi(map);
        if (!Null.check(backLi)) {
            for (int j = 0; j < backLi.size(); j++) {
                backLi.get(j).setLineId(j + 1);
                backTotal += backLi.get(j).getAmount() * backLi.get(j).getCurrency().getChange();
            }
        }
        backModel.setWrappedData(backLi);
        Double costTotal = 0d;
        Double advanceTotal = 0d;
        for (int i = 0; i < costLi.size(); i++) {
            costTotal += costLi.get(i).getFoodCost() + costLi.get(i).getMixCost() + costLi.get(i).getOther() + costLi.get(i).getPersonalCost() + costLi.get(i).getStayCost() + costLi.get(i).getTrafficCost();
        }
        if (!Null.check(backLi)) {
            for (int i = 0; i < backLi.size(); i++) {
                advanceTotal += backLi.get(i).getAdvance();
            }
        }
        abroad.setCheckaccount(costTotal - advanceTotal);
        forCashPaid();

        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            //System.out.println("submitOrNot=" + submitOrNot);
        }
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        NavigationTool.getSelectedUrl("/page/pay/payment/operation/abroadGroupPay.xhtml");
    }

    //生成支付令
    public void buildpaycode() {
        //System.out.println("buildpaycode !!!");
        if (abroad.getCostitem().getCode().trim().length() != 0) {
            if (abroad.getBudgetSource() != null) {
                if (abroad.getCostClass() != null) {
                    if (abroad.getCostTypes().getCode().trim().length() != 0) {
                        String pcode = PayCodeConstants.buildPayCodeForLoanBill(abroad);
                        abroad.setPaycode(pcode);
                    } else {
                        ToolKit.msgs_err("请选择支出渠道");
                        FacesContext.getCurrentInstance().renderResponse();
                    }
                } else {
                    ToolKit.msgs_err("请选择支出类别");
                    FacesContext.getCurrentInstance().renderResponse();
                }
            } else {
                ToolKit.msgs_err("请选择预算来源");
                FacesContext.getCurrentInstance().renderResponse();
            }
        } else {
            ToolKit.msgs_err("请选择经济分类");
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void checkandRep() {
        if (abroad.getCostitem().getCode() == null) abroad.getCostitem().setCode("");
        if (abroad.getBudgetSource() == null) abroad.setBudgetSource("");
        if (abroad.getCostClass() == null) abroad.setCostClass("");
        if (abroad.getCostTypes().getCode() == null) abroad.getCostTypes().setCode("");
        if (abroad.getPaycode() == null) abroad.setPaycode("");

        if (abroad.getAuditDate() == null || Null.check(abroad.getAuditor())) {
            ToolKit.msgs_err("您无权限审核！");
        } else {
            pass();
            goback();
        }
    }

    //支付检查
    public void checkPayandRep() {
        String payStatus = abroad.getNumberStatus();
        abroad.setNumberStatus("2");//防止填写“支付完毕”后单据未成功确认支付
        if (Null.check(abroad.getPayStyle().getCode())) {
            ToolKit.msgs_err("请选择支付方式");
        } else if (abroad.getPayaccount() == null) {
            ToolKit.msgs_err("请输入支付金额");
        } else if (abroad.getPayDate() == null) {
            ToolKit.msgs_err("请选择支付日期");
        } else if ("1".equals(payWayType) && Null.check(abroad.getReceive())) {
            ToolKit.msgs_err("收款人不能为空!");
        } else if (abroad.getCashPaid() == null) {
            ToolKit.msgs_err("是否现金付讫！");
        } else if (Null.check(payStatus)) {
            ToolKit.msgs_err("是否支付完毕！");
        } else if ("1".equals(abroad.getCashPaid()) && abroad.getTicketcode().length() != 0) {
            ToolKit.msgs_err("现金付讫不需填写支付凭证号");
        } else if ("0".equals(abroad.getCashPaid()) && Null.check(abroad.getTicketcode())) {
            ToolKit.msgs_err("请填写支付凭证号");
        } else {
            if ("0".equals(abroad.getCashPaid())) {
                String str = abroad.getNumber() + abroad.getTicketcode();
                abroad.setTicketcode(str);
            }
            abroad.setNumberStatus(payStatus);
            pay();  //支付
            NavigationTool.getSelectedUrl("/page/pay/payment/table/queryAbroadGroupPayli.xhtml");
        }
    }

    public void pay() {
        //abroad.setNumberStatus("4");
        abroad.setPayer(curPerNum().trim());

        Map map = new HashMap();
        map.put("number", abroad.getNumber());
        map.put("voutype", abroad.getVoutype().trim());
        map.put("numstatus", abroad.getNumberStatus());
        map.put("payaccount", abroad.getPayaccount());
        map.put("paystyle", payWay);
        map.put("ticketcode", abroad.getTicketcode());
        map.put("payer", abroad.getPayer());
        map.put("paydate", abroad.getPayDate());
        map.put("cashPaid", abroad.getCashPaid());
        map.put("receive", Null.convert(abroad.getReceive()));
        map.put("orgCode", curOrgCode().trim());
        AbroadGroupCheckImpl.updateAbroadGroupforPay(map);

        queryAbroadList();

        //Person receiver = PersonImpl.queryByPerNumber(abroad.getUser().getCpsn_number().trim());
        //Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
        //ToolsMethed.sendMail(sender, receiver, "支付成功", "支付  Done!!!");
        ToolKit.msgs_info("支付成功!");
    }

    //生成收款人code
    public String autoReceiveCode() {
        String maxCode = AbroadGroupCheckImpl.getReceiveCode(curOrgCode().trim());
        if (Null.check(maxCode)) {
            maxCode = "0";
        }
        return String.format("%06d%n", Integer.parseInt(maxCode.trim()) + 1).trim();
    }

    public void pass() {
        abroad.setNumberStatus("2");
        abroad.setAuditor(curPerNum().trim());

        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("number", abroad.getNumber());
        map.put("voutype", abroad.getVoutype());
        map.put("numstatus", abroad.getNumberStatus());
        map.put("checkaccount", abroad.getCheckaccount());
        map.put("budgetsource", abroad.getBudgetSource());
        map.put("eoc", abroad.getCostitem().getCode());
        map.put("paycode", abroad.getPaycode());
        map.put("costclass", abroad.getCostClass());
        map.put("costtype", abroad.getCostTypes().getCode());
        map.put("auditor", abroad.getAuditor());
        map.put("auditdate", abroad.getAuditDate());
        AbroadGroupCheckImpl.updateAbroadGroupforCheck(map);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(abroad.getNumber());
        info.setVouType(abroad.getVoutype());
        info.setCheckInfo(abroad.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

//        Person receiver = PersonImpl.queryByPerNumber(abroad.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
//        ToolsMethed.sendMail(sender, receiver, "审核通过", "审核  Done!!!");
        initStatus();
    }

    private void initCheckValue(Expense abroad) {
        this.abroad = abroad;
        builds();
        if (abroad.getCostitem().getCode() == null) abroad.getCostitem().setCode("");
        if (abroad.getBudgetSource() == null) abroad.setBudgetSource("");
        if (abroad.getCostClass() == null) abroad.setCostClass("");
        if (abroad.getCostTypes().getCode() == null) abroad.getCostTypes().setCode("");
        if (abroad.getPaycode() == null) abroad.setPaycode("");
    }

    public void passWithParam(Expense abroad) {
        initCheckValue(abroad);

        abroad.setNumberStatus("2");
        abroad.setAuditor(curPerNum().trim());

        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("number", abroad.getNumber());
        map.put("voutype", abroad.getVoutype());
        map.put("numstatus", abroad.getNumberStatus());
        map.put("checkaccount", abroad.getCheckaccount());
        map.put("budgetsource", abroad.getBudgetSource());
        map.put("eoc", abroad.getCostitem().getCode());
        map.put("paycode", abroad.getPaycode());
        map.put("costclass", abroad.getCostClass());
        map.put("costtype", abroad.getCostTypes().getCode());
        map.put("auditor", abroad.getAuditor());
        map.put("auditdate", abroad.getAuditDate());
        AbroadGroupCheckImpl.updateAbroadGroupforCheck(map);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(abroad.getNumber());
        info.setVouType(abroad.getVoutype());
        info.setCheckInfo(abroad.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

//        Person receiver = PersonImpl.queryByPerNumber(abroad.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
//        ToolsMethed.sendMail(sender, receiver, "审核通过", "审核  Done!!!");
        initStatus();
    }

    public void goback() {
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        abroadList = AbroadGroupCheckImpl.getAbroadPayList(map);
        abroadModel.setWrappedData(abroadList);
        NavigationTool.getSelectedUrl("/page/pay/check/table/queryAbroadGroupList.xhtml");

    }

    public void goBackPayList() {
        queryAbroadList();
//        Map map = new HashMap();
//        map.put("orgCode", curOrgCode().trim());
//        abroadList = AbroadGroupCheckImpl.getAbroadPayList(map);
//        abroadModel.setWrappedData(abroadList);
        NavigationTool.getSelectedUrl("/page/pay/payment/table/queryAbroadGroupPayli.xhtml");
    }

    public void back() {
        abroad.setNumberStatus("3");
//        Person receiver = PersonImpl.queryByPerNumber(abroad.getUser().getCpsn_number().trim());
//        Person sender = PersonImpl.queryByPerNumber(curPerNum().trim());
//        ToolsMethed.sendMail(sender, receiver, "审核未通过", "请重新修改!!!");

        Map map = new HashMap();
        map.put("number", abroad.getNumber().trim());
        map.put("orgCode", curOrgCode().trim());
        IbatisTemplate.update("loanbill.voucherBack", map);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(abroad.getNumber());
        info.setVouType(abroad.getVoutype());
        info.setCheckInfo(abroad.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

        initStatus();
        goback();
    }

    public void cancelChecked() {
        IbatisTemplate.update("loanbill.voucherRescind", abroad);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(abroad.getNumber());
        info.setVouType(abroad.getVoutype());
        VoucherPubImpl.deleteCheckInfo(info);

        initStatus();
        goback();
    }

    public void rescind() {
        IbatisTemplate.update("loanbill.payVoucherRescind", abroad);
        initStatus();
        goback();
        NavigationTool.getSelectedUrl("/page/pay/payment/table/queryAbroadGroupPayli.xhtml");
    }

    //生成退领人民币总金额
    public void buildBackTotal() {
        backTotal = 0d;
        List<AbroadGroupBackorCollar> backli = (ArrayList) backModel.getWrappedData();
        for (AbroadGroupBackorCollar bl : backli) {
            backTotal += bl.getAmount() * bl.getCurrency().getChange();
        }
    }

    public void builds() {
        showCostBackDetail();
        //System.out.println("getNumberStatus : " + abroad.getNumberStatus().trim());
        if ("0".equals(abroad.getNumberStatus().trim()) && "C".equalsIgnoreCase(curPerRole().trim())) {
            abroad.setAuditor(curPerName().trim());
            abroad.setAuditDate(new Date());
            //System.out.println("setAuditor");
            //核定金额
            Double costTotal = 0d;
            Double advanceTotal = 0d;
            for (int i = 0; i < costLi.size(); i++) {
                costTotal += costLi.get(i).getFoodCost() + costLi.get(i).getMixCost() + costLi.get(i).getOther() + costLi.get(i).getPersonalCost() + costLi.get(i).getStayCost() + costLi.get(i).getTrafficCost();
            }
            if (!Null.check(backLi)) {
                for (int i = 0; i < backLi.size(); i++) {
                    advanceTotal += backLi.get(i).getAdvance();
                }
            }
            abroad.setCheckaccount(costTotal - advanceTotal);
        }

        payWay = abroad.getPayStyle().getCode();

        if ("2".equals(abroad.getNumberStatus().trim()) && "P".equalsIgnoreCase(curPerRole().trim())) {
            abroad.setPayer(curPerName().trim());
            abroad.setPayaccount(abroad.getCheckaccount());
            abroad.setPayDate(new Date());
            //System.out.println("setPayer");
            forCashPaid();
        }

    }

    public void showCostBackDetail() {
        Map map = new HashMap();
        map.put("number", abroad.getNumber());
        map.put("voutype", "6");
        map.put("orgCode", curOrgCode().trim());

        costLi = AbroadGroupCheckImpl.getAbroadCostLi(map);
        for (int i = 0; i < costLi.size(); i++) {
            costLi.get(i).setLineId(i + 1);
        }
        costModel.setWrappedData(costLi);

        backLi = AbroadGroupCheckImpl.getAbroadBackLi(map);
        for (int j = 0; j < backLi.size(); j++) {
            backLi.get(j).setLineId(j + 1);
        }
        backModel.setWrappedData(backLi);

        backTotal = 0d;
        backLi = AbroadGroupCheckImpl.getAbroadBackLi(map);
        if (!Null.check(backLi)) {
            for (int j = 0; j < backLi.size(); j++) {
                backLi.get(j).setLineId(j + 1);
                backTotal += backLi.get(j).getAmount() * backLi.get(j).getCurrency().getChange();
            }
        }
        backModel.setWrappedData(backLi);

    }

    public void forCashPaid() {
        if (!Null.check(abroad.getPayStyle().getType()) && Null.check(abroad.getCashPaid())) {
            if (abroad.getPayStyle().getType().equals("0")) {
                abroad.setCashPaid("1");
            } else {
                abroad.setCashPaid("0");
            }
        }
    }

    public void initCheckViewList() {
        Map map = new HashMap();
        map.put("voustatus", "0");
        map.put("orgCode", curOrgCode().trim());
        abroadList = AbroadGroupCheckImpl.queryAbroadViewList(map);
        abroadCheckViewModel.setWrappedData(abroadList);
    }

    public void showFromCheckView(Expense expense, DataModel viewModel) {
        abroad = expense;
        index = viewModel.getRowIndex();
        abroadList = (List<Expense>) viewModel.getWrappedData();
        linkedli.clear();
        linkedli.addAll(abroadList);
        showAble = false;
        abroad.setAuditDate(new Date());
        abroad.setPerson(abroad.getUser().getCpsn_name());
        builds();
        Double costTotal = 0d;
        Double advanceTotal = 0d;
        for (int i = 0; i < costLi.size(); i++) {
            costTotal += costLi.get(i).getFoodCost() + costLi.get(i).getMixCost() + costLi.get(i).getOther() + costLi.get(i).getPersonalCost() + costLi.get(i).getStayCost() + costLi.get(i).getTrafficCost();
            advanceTotal += backLi.get(i).getAdvance();
        }
        abroad.setCheckaccount(costTotal - advanceTotal);

        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            //System.out.println("submitOrNot=" + submitOrNot);
        }
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        NavigationTool.getSelectedUrl("/page/pay/check/operation/abroadGroupCheck.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void showFromPayView(Expense expense, DataModel viewModel) {
        abroad = expense;
        index = viewModel.getRowIndex();
        abroadList = (List<Expense>) viewModel.getWrappedData();
        linkedli.clear();
        linkedli.addAll(abroadList);
        showAble = false;
        abroad.setPayer(curPerName().trim());
        abroad.setPayDate(new Date());
        abroad.setPayaccount(abroad.getCheckaccount());
        abroad.setPerson(abroad.getUser().getCpsn_name());
        abroad.setReceive(abroad.getPerson());
        payWay = abroad.getPayStyle().getCode();

        Map map = new HashMap();
        map.put("number", abroad.getNumber());
        map.put("voutype", "6");
        map.put("orgCode", curOrgCode().trim());
        costLi = AbroadGroupCheckImpl.getAbroadCostLi(map);
        for (int i = 0; i < costLi.size(); i++) {
            costLi.get(i).setLineId(i + 1);
        }
        costModel.setWrappedData(costLi);
        backTotal = 0d;
        backLi = AbroadGroupCheckImpl.getAbroadBackLi(map);
        for (int j = 0; j < backLi.size(); j++) {
            backLi.get(j).setLineId(j + 1);
            backTotal += backLi.get(j).getAmount() * backLi.get(j).getCurrency().getChange();
        }
        backModel.setWrappedData(backLi);
        Double costTotal = 0d;
        Double advanceTotal = 0d;
        for (int i = 0; i < costLi.size(); i++) {
            costTotal += costLi.get(i).getFoodCost() + costLi.get(i).getMixCost() + costLi.get(i).getOther() + costLi.get(i).getPersonalCost() + costLi.get(i).getStayCost() + costLi.get(i).getTrafficCost();
            advanceTotal += backLi.get(i).getAdvance();
        }
        abroad.setCheckaccount(costTotal - advanceTotal);


        if (abroad.getNumberStatus().trim().equals("0")) {
            submitOrNot = true;
        } else {
            submitOrNot = false;
            //System.out.println("submitOrNot=" + submitOrNot);
        }
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        NavigationTool.getSelectedUrl("/page/pay/payment/operation/abroadGroupPay.xhtml");
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("出国差旅费列表");
        String[] excelColumns = initTabeleHeader();
        List<Expense> rows = abroadList;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("出国差旅费列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        TravelInputBean.exportExcel(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeader() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "出差事由", "报销金额", "预算项目", "报销人", "部门", "支出类别", "预算来源",
            "经济分类", "支出渠道", "支付令", "核定金额", "审核日期", "审核人", "支付金额", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense eit, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        HSSFCellStyle dstyled = demoWorkBook.createCellStyle();
        dstyled.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);

        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(eit.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(eit.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(eit.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getTotal()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(eit.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(eit.getUser().getCpsn_name()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(eit.getDept().getName()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.formateCostClass().get(eit.getCostClass())));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(eit.getBudgetSource()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(eit.getCostitem().getName()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(eit.getCostTypes().getName()));
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPaycode()));

        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getCheckaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(14);
        if (eit.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(15);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAuditor()));
        cell = row.createCell(16);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getPayaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(17);
        if (eit.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(18);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPayer()));

    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //getter and setter
    public Expense getAbroad() {
        return abroad;
    }

    public void setAbroad(Expense abroad) {
        this.abroad = abroad;
    }

    public AbroadGroupBackorCollar getBack() {
        return back;
    }

    public void setBack(AbroadGroupBackorCollar back) {
        this.back = back;
    }

    public List<AbroadGroupBackorCollar> getBackLi() {
        return backLi;
    }

    public void setBackLi(List<AbroadGroupBackorCollar> backLi) {
        this.backLi = backLi;
    }

    public AbroadGroupCost getCost() {
        return cost;
    }

    public void setCost(AbroadGroupCost cost) {
        this.cost = cost;
    }

    public List<AbroadGroupCost> getCostLi() {
        return costLi;
    }

    public void setCostLi(List<AbroadGroupCost> costLi) {
        this.costLi = costLi;
    }

    public AbroadGroupCurrency getCurrency() {
        return currency;
    }

    public void setCurrency(AbroadGroupCurrency currency) {
        this.currency = currency;
    }

    public AbroadGroupGroup getGroup() {
        return group;
    }

    public void setGroup(AbroadGroupGroup group) {
        this.group = group;
    }

    public List<AbroadGroupCurrency> getCurrencyLi() {
        return currencyLi;
    }

    public void setCurrencyLi(List<AbroadGroupCurrency> currencyLi) {
        this.currencyLi = currencyLi;
    }

    public List<AbroadGroupGroup> getGroupLi() {
        return groupLi;
    }

    public void setGroupLi(List<AbroadGroupGroup> groupLi) {
        this.groupLi = groupLi;
    }

    public DataModel getBackModel() {
        return backModel;
    }

    public void setBackModel(DataModel backModel) {
        this.backModel = backModel;
    }

    public DataModel getCostModel() {
        return costModel;
    }

    public void setCostModel(DataModel costModel) {
        this.costModel = costModel;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isDeleteable() {
        return deleteable;
    }

    public void setDeleteable(boolean deleteable) {
        this.deleteable = deleteable;
    }

    public boolean isPrintAble() {
        return printAble;
    }

    public void setPrintAble(boolean printAble) {
        this.printAble = printAble;
    }

    public boolean isSaveOrNot() {
        return saveOrNot;
    }

    public void setSaveOrNot(boolean saveOrNot) {
        this.saveOrNot = saveOrNot;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public boolean isSubmitOrNot() {
        return submitOrNot;
    }

    public void setSubmitOrNot(boolean submitOrNot) {
        this.submitOrNot = submitOrNot;
    }

    public boolean isUpdateOrNot() {
        return updateOrNot;
    }

    public void setUpdateOrNot(boolean updateOrNot) {
        this.updateOrNot = updateOrNot;
    }

    public Disabled getDis() {
        return dis;
    }

    public void setDis(Disabled dis) {
        this.dis = dis;
    }

    public List<Expense> getAbroadList() {
        return abroadList;
    }

    public void setAbroadList(List<Expense> abroadList) {
        this.abroadList = abroadList;
    }

    public QueryVouchers getQta() {
        return qta;
    }

    public void setQta(QueryVouchers qta) {
        this.qta = qta;
    }

    public DataModel<Expense> getAbroadModel() {
        return abroadModel;
    }

    public void setAbroadModel(DataModel abroadModel) {
        this.abroadModel = abroadModel;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public LinkedList<Expense> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<Expense> linkedli) {
        this.linkedli = linkedli;
    }

    public ClassCode getClasscode() {
        return classcode;
    }

    public void setClasscode(ClassCode classcode) {
        this.classcode = classcode;
    }

    public List<ClassCode> getClasslist() {
        return classlist;
    }

    public void setClasslist(List<ClassCode> classlist) {
        this.classlist = classlist;
    }

    public int getCostLiSize() {
        return costLiSize;
    }

    public void setCostLiSize(int costLiSize) {
        this.costLiSize = costLiSize;
    }

    public List<SelectItem> getSelectItemList() {
        return selectItemList;
    }

    public void setSelectItemList(List<SelectItem> selectItemList) {
        this.selectItemList = selectItemList;
    }
    //

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    private String curPerRole() {
        return LoginParam.getPer().getRole();
    }

    public Double getBackTotal() {
        return backTotal;
    }

    public void setBackTotal(Double backTotal) {
        this.backTotal = backTotal;
    }

    public List<SelectItem> getPayStyleList() {
        return payStyleList;
    }

    public void setPayStyleList(List<SelectItem> payStyleList) {
        this.payStyleList = payStyleList;
    }

    public String getPayWay() {
        return payWay;
    }

    public void setPayWay(String payWay) {
        this.payWay = payWay;
    }

    public String getPayWayType() {
        return payWayType;
    }

    public void setPayWayType(String payWayType) {
        this.payWayType = payWayType;
    }

    public DataModel getAbroadCheckViewModel() {
        return abroadCheckViewModel;
    }

    public void setAbroadCheckViewModel(DataModel abroadCheckViewModel) {
        this.abroadCheckViewModel = abroadCheckViewModel;
    }

    public List<SelectItem> getStatusList() {
        List<SelectItem> statusList = new ArrayList<SelectItem>();
        statusList.add(new SelectItem("0,3", "未审核"));
        statusList.add(new SelectItem("2,4,6", "已审核"));
        return statusList;
    }

    public List<SelectItem> getPayStatusList() {
        List<SelectItem> payStatusList = new ArrayList<SelectItem>();
        payStatusList.add(new SelectItem("0,2,3", "未支付"));
        payStatusList.add(new SelectItem("4,6", "已支付"));
        return payStatusList;
    }

    public DataModel<FinancialProject> getFinProjModel() {
        return finProjModel;
    }

    public void setFinProjModel(DataModel<FinancialProject> finProjModel) {
        this.finProjModel = finProjModel;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
